﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ClearCache : MonoBehaviour {

    private static readonly string cacheLessonesKey = "cacheLessones";
    private static readonly string cacheCoursewareKey = "cacheCourseware";

    // -------  templet ----------
    public GameObject templet = null;
    // -------  templet end ------

    private static ClearCache instance = null;

    private static bool isCourseware = false;
    public static void Show( bool courseware )
    {
        isCourseware = courseware;

        instance.gameObject.SetActive(true);
    }

    private void Awake()
    {
        instance = this;
    }

    private void Start()
    {
        gameObject.SetActive(false);
    }

    void OnEnable()
    {
        Init();
    }

    void Init()
    {
        Erase();

        // 获取
        List<string> li = null;

        if (!isCourseware)
            li = GetCacheLessones();
        else
            li = GetCacheCourseware();

        if (li.Count == 0)
            return;

        // 初始化N个
        foreach( var item in li)
        {
            GameObject obj = Instantiate(templet) as GameObject;
            obj.SetActive(true);
            obj.transform.parent = templet.transform.parent;
            obj.name = item;
            obj.transform.localScale = templet.transform.localScale;

            Text t = obj.GetComponentInChildren<Text>();
            t.text = "第" + item + "课";
        }

        
    }

    List<string> GetChoosenLessones()
    {
        List<string> res = new List<string>();

        for( int i = 1; i < templet.transform.parent.childCount; i++ )
        {
            GameObject o = templet.transform.parent.GetChild(i).gameObject;
            Toggle t = o.GetComponent<Toggle>();
            if ( t.isOn )
            {
                res.Add(o.name);
            }
        }

        return res;
    }



    void Erase()
    {
        for( int i = 1; i < templet.transform.parent.childCount; i++ )
        {
            GameObject.Destroy(templet.transform.parent.GetChild(i).gameObject);
        }
    }

    public static List<string> GetCacheLessones()
    {
        string cacheLessones = PlayerPrefs.GetString(cacheLessonesKey);
        Debug.Log("cache lesson json string:" + cacheLessones);
        if (string.IsNullOrEmpty(cacheLessones))
            return new List<string>();

        List<object> res = MiniJSON.Json.Deserialize(cacheLessones) as List<object>;
        List<int> r = new List<int>();
        foreach(var item in res )
        {
            r.Add(Convert.ToInt32( item ));
            
        }

        r.Sort();

        List<string> ress = new List<string>();
        foreach( var item in r )
        {
            ress.Add(item.ToString());
        }
        return ress;

    }



    public static List<string> GetCacheCourseware()
    {
        string cacheLessones = PlayerPrefs.GetString(cacheCoursewareKey);
        Debug.Log("cache courseware json string:" + cacheLessones);
        if (string.IsNullOrEmpty(cacheLessones))
            return new List<string>();

        List<object> res = MiniJSON.Json.Deserialize(cacheLessones) as List<object>;
        List<int> r = new List<int>();
        foreach (var item in res)
        {
            r.Add(Convert.ToInt32(item));

        }

        r.Sort();

        List<string> ress = new List<string>();
        foreach (var item in r)
        {
            ress.Add(item.ToString());
        }
        return ress;

    }

    public static void AddCacheLesson(int id)
    {
        AddCacheLesson(id.ToString());
    }

    public static void AddCacheLesson(string id)
    {
        List<string> res = GetCacheLessones();
        if (res.Contains(id))
            return;

        res.Add(id);

        // 转json
        string cache = MiniJSON.Json.Serialize(res);
        PlayerPrefs.SetString(cacheLessonesKey, cache);
    }

    private void DelCacheLesson(List<string> ids )
    {
        List<string> res = GetCacheLessones();
        if (res.Count == 0)
            return;

        foreach( var item in ids)
        {
            res.Remove(item);

            // 真正的清除缓存操作
            ClearCacheByLesson(item);
        }

        // 转json
        string cache = MiniJSON.Json.Serialize(res);
        PlayerPrefs.SetString(cacheLessonesKey, cache);
    }

    public static void AddCacheCourseware(int id)
    {
        AddCacheCourseware(id.ToString());
    }

    public static void AddCacheCourseware(string id)
    {
        List<string> res = GetCacheCourseware();
        if (res.Contains(id))
            return;

        res.Add(id);

        // 转json
        string cache = MiniJSON.Json.Serialize(res);
        PlayerPrefs.SetString(cacheCoursewareKey, cache);
    }

    private void DelCacheCourseware(List<string> ids)
    {
        List<string> res = GetCacheCourseware();
        if (res.Count == 0)
            return;

        foreach (var item in ids)
        {
            res.Remove(item);

            // 真正的清除缓存操作
            ClearKejianCacheByLesson(item);
        }

        // 转json
        string cache = MiniJSON.Json.Serialize(res);
        PlayerPrefs.SetString(cacheCoursewareKey, cache);
    }



    private List<string> ClearCacheByType(string typ, string id)
    {
        List<string> li = new List<string>();
        if ("video" == typ)
        {

            VideoCfgData.VideoCfg cfg = DataManager.videoCfgData.GetCfg(id);
            if (cfg == null)
                return li;

            ResLoader.DelDownload(cfg.urlVideo1);
            ResLoader.DelDownload(cfg.urlAudio1);

            if (cfg.VideoType == "multi")
            {

                ResLoader.DelDownload(cfg.urlVideo2);
                ResLoader.DelDownload(cfg.urlAudio2);
                ResLoader.DelDownload(cfg.urlImage);
            }
        }
        else if ("game" == typ)
        {

            GameCfgData.GameCfg cfg = DataManager.gameCfgData.GetCfg(id);
            if (cfg == null)
                return li;

            ResLoader.DelDownload(cfg.mansu.urlMusic);
            ResLoader.DelDownload(cfg.kuaisu.urlMusic);
            ResLoader.DelDownload(cfg.urlVideo);
        }
        else if ( "yiguzuoqi" == typ )
        {
            YiguzuoqiCfgData.YiguzuoqiCfg cfg = DataManager.yiguzuoqiCfgData.GetCfg(id);
            if (cfg == null)
                return li;

            ResLoader.DelDownload(cfg.urlKuaisu);
            ResLoader.DelDownload(cfg.urlMansu);
            ResLoader.DelDownload(cfg.urlZhongsu);
            ResLoader.DelDownload(cfg.urlYanzousudu);
        }

        return li;
    }

    public void ClearCacheByLesson(string lessonID)
    {
        Dictionary<string, LessonCfgData.LessonCfg> l = DataManager.lessonCfgData.GetLesson(lessonID);
        if (l == null || l.Count == 0)
            return;

        List<string> l1 = ClearCacheByType(l["tingkan"].lessonType, l["tingkan"].id);
        List<string> l2 = ClearCacheByType(l["wannao"].lessonType, l["wannao"].id);
        List<string> l3 = ClearCacheByType(l["niutiao"].lessonType, l["niutiao"].id);
        List<string> l4 = ClearCacheByType(l["qiaoda"].lessonType, l["qiaoda"].id);
        List<string> l5 = ClearCacheByType(l["yiguzuoqi"].lessonType, l["yiguzuoqi"].id);
    }

    public void ClearKejianCacheByLesson( string lesssonID )
    {
        KejianCfgData.KejianCfg cfg = DataManager.kejianCfgData.GetCfg(lesssonID);
        if (cfg == null)
            return;

        foreach( var item in cfg.kejian )
        {
            ResLoader.DelDownload(item);
        }

        foreach (var item in cfg.audio)
        {
            ResLoader.DelDownload(item);
        }

        foreach (var item in cfg.video)
        {
            ResLoader.DelDownload(item);
        }

        foreach (var item in cfg.drum)
        {
            ResLoader.DelDownload(item);
        }

        foreach (var item in cfg.dancing)
        {
            ResLoader.DelDownload(item);
        }


    }


    public void OnBtnClearCourseware()
    {
        List<string> res = GetChoosenLessones();
        if (res.Count == 0)
            return;

        Loading.GetInstance().StartLoading();


        DelCacheCourseware(res);
        Loading.GetInstance().EndLoading();

        OnBtnReturn();
    }

    public void OnBtnClearCache()
    {
        List<string> res = GetChoosenLessones();
        if (res.Count == 0)
            return;

        if ( isCourseware )
        {
            OnBtnClearCourseware();
            return;
        }

        Loading.GetInstance().StartLoading();
            

        DelCacheLesson(res);
        Loading.GetInstance().EndLoading();

        OnBtnReturn();

    }

    public void OnBtnReturn()
    {

        Debug.Log("OnBtnReturn");

        gameObject.SetActive(false);

        lessonUI.GetInstance().ShowLessonList();
    }

}
